import React from 'react';
import "@/styles/_news.scss";
import { Spin, Icon, Tooltip, message, Drawer, Button, Input, DatePicker, Breadcrumb } from 'antd';
import { postFn } from "@/api/commonApi";
import { getInnerText, getLocalStorage, deleteLocalStorage, saveLocalStorage } from "@/utils";
import moment from "moment";
import 'moment/locale/zh-cn';
moment.locale('zh-cn');
const { TextArea } = Input;

class News extends React.Component<any, any>{
    constructor(props: any) {
        super(props);
        this.state = {
            // 首页加载
            loading: false,
            currentUrl: this.props.match.params.code,
            newsTabData: [
                {
                    title: "通知公告",
                    code: "anc"
                },
                {
                    title: "行业动态",
                    code: "ln"
                },
                {
                    title: "优惠促销",
                    code: "pt"
                },
                {
                    title: "帮助中心",
                    code: "hc"
                },
            ],
            // 一进来所有数据
            allData: [],
            // 当前tab的数据
            contentData: [],
            // 打开详情
            showDetail: getLocalStorage('showDetail') || {
                open: false,
                content: {},
            },
            // 编辑此页 / 新增一条
            isEdit: true,
            editContent: {
                open: false,
                content: {}
            },
            // 编辑加载
            editLoading: false,
            // 权限账号token
            token: "admin1"
        };
    }
    componentDidMount() {
        this.getNewsData();

    }
    componentDidUpdate(nextProps: any) {
        if (this.props.location !== nextProps.location) {
            let currentUrl = this.props.match.params.code;
            this.setState({ currentUrl: currentUrl });
            this.getCurrenTabData(currentUrl);
        }
    }
    render() {
        return (
            <div className="i7b-news-anc">
                <div className="n-a-h"></div>
                <div className="n-a-tab common-tabs">
                    <div className="common-width tabs-c">
                        {this.state.newsTabData.map((item: any, inx: number) => {
                            return (
                                <span key={inx} style={{ width: `${100 / this.state.newsTabData.length}%` }}
                                    className={`${this.state.currentUrl === item.code ? 'highlight' : ''}`}
                                    onClick={this.tabsChange.bind(this, item)}>
                                    {item.title}
                                </span>
                            )
                        })}
                    </div>
                </div>
                <div className="n-a-body">
                    <div className="common-width" style={{ paddingBottom: 10, color: "rgba(0, 0, 0, 0.45)", fontSize: 12 }}>
                        <Icon type="home" className="mr-10" style={{ color: "#3946d2", position: "relative", top: -1 }} />
                        你当前的位置：
                        <Breadcrumb separator=">" style={{ display: "inline-block", fontSize: 12 }}>
                            <Breadcrumb.Item>
                                <a href="/">网站首页</a>
                            </Breadcrumb.Item>
                            <Breadcrumb.Item>
                                <a href={`#/news/${this.state.currentUrl}`}>新闻资讯</a>
                            </Breadcrumb.Item>
                            <Breadcrumb.Item>
                                {this.state.newsTabData.map((item: any, i: number) => {
                                    return (
                                        <span key={i} style={{ color: "rgba(0, 0, 0, 0.45)" }}>{item.code === this.state.currentUrl ? item.title : ""}</span>
                                    )
                                })}
                            </Breadcrumb.Item>
                        </Breadcrumb>
                    </div>
                    {this.state.showDetail.open ?
                        <div className="show-detail common-width">
                            <h1>
                                {this.state.showDetail.content.title}
                                <div className="icon-box">
                                    <Tooltip title={<span>返回目录</span>}>
                                        <Icon type="import" className="mr-10" onClick={this.backList.bind(this)} />
                                    </Tooltip>
                                    <Tooltip title={<span>编辑此页</span>}>
                                        <Icon type="edit" onClick={this.editContent.bind(this)} />
                                    </Tooltip>
                                </div>
                                <span className="date-span">发布于： {this.state.showDetail.content.date}</span>
                            </h1>
                            <div className="xr-html" dangerouslySetInnerHTML={{ __html: this.state.showDetail.content.content }}></div>
                        </div> :
                        <Spin spinning={this.state.loading} delay={200}>
                            <div className="common-width n-a-c">
                                <ul>
                                    {this.state.contentData.map((item: any, i: number) => {
                                        return (
                                            <li className="fl" key={i}>
                                                <span className="date-span"><Icon type="clock-circle" className="mr-10" />{item.date}</span>
                                                <h3 className="yc">{item.title}</h3>
                                                <div className="content" dangerouslySetInnerHTML={{ __html: getInnerText(item.content) }}></div>
                                                <div className="more" onClick={this.lookDetail.bind(this, item)}>
                                                    <span>···</span>
                                                </div>
                                            </li>
                                        )
                                    })}
                                    <li className="fl add-li">
                                        <Button onClick={this.addList.bind(this)}>新增动态</Button>
                                    </li>
                                    <br className="clear" />
                                </ul>
                            </div>
                        </Spin>
                    }
                </div>
                <Drawer
                    title={`${this.state.isEdit ? '编辑此页' : "新增动态"}`}
                    width={520}
                    onClose={this.closeEditContent.bind(this)}
                    visible={this.state.editContent.open}
                    bodyStyle={{ paddingBottom: 80 }}
                    maskClosable={false}
                >
                    <Spin spinning={this.state.editLoading} delay={200}>
                        {this.state.isEdit ?
                            <div className="mb-10">
                                <div className="mb-10">
                                    <Icon type="info-circle" className="mr-10" style={{ color: "#faad14" }} />
                                    本次修改如未登陆权限账号只作临时演示，刷新即恢复！
                                </div>
                                <div className="mb-10">
                                    <Icon type="info-circle" className="mr-10" style={{ color: "#faad14" }} />
                                    <span className="mr-10">如果您有更好的排版，请</span>
                                    <Button href="tencent://Message/?Uin=2152860&amp;websiteName=q-zone.qq.com&amp;Menu=yes"
                                        icon="qq" size={"small"}>联系我们</Button>
                                </div>
                            </div> : ""}
                        <br />
                        <div>
                            <strong className="mr-10">{this.state.isEdit ? '修改' : "新增"}日期</strong>
                            <DatePicker value={moment(this.state.editContent.content.date, 'YYYY-MM-DD')}
                                onChange={(m, v) => { this.contentChange("date", v) }}
                            />
                        </div>
                        <br />
                        <br />
                        <div>
                            <strong className="mb-10" style={{ display: "block" }}>{this.state.isEdit ? '修改' : "新增"}标题</strong>
                            <Input value={this.state.editContent.content.title} onChange={this.contentChange.bind(this, 'title')} />
                        </div>
                        <br />
                        <br />
                        <div>
                            <strong className="mb-10" style={{ display: "block" }}>{this.state.isEdit ? '修改' : "新增"}内容</strong>
                            <div className="mb-10">
                                <Icon type="info-circle" className="mr-10" style={{ color: "green" }} />
                                前往 <a href="http://kindeditor.net/demo.php" target="_blank" rel="noopener noreferrer">在线HTML编辑器</a> 编辑内容。
                        </div>
                            <div className="mb-10">
                                <Icon type="info-circle" className="mr-10" style={{ color: "green" }} />
                                编辑好后点编辑器左上角复制源码复制粘贴在下面输入框即可！
                        </div>
                            <TextArea rows={8} onChange={this.contentChange.bind(this, 'content')}
                                value={this.state.editContent.content.content} />
                        </div>
                    </Spin>
                    <div
                        style={{
                            position: 'absolute',
                            right: 0,
                            bottom: 0,
                            width: '100%',
                            borderTop: '1px solid #e9e9e9',
                            padding: '10px 16px',
                            background: '#fff',
                            textAlign: 'right',
                        }}
                    >
                        <Button onClick={this.closeEditContent.bind(this)} style={{ marginRight: 8 }}>
                            取消
                        </Button>
                        <Button onClick={this.confirmEditContent.bind(this)} type="primary">
                            保存
                        </Button>
                    </div>
                </Drawer>
            </div >
        )
    }
    // tab切换
    tabsChange(item: any) {
        if (this.state.currentUrl === item.code) return;
        this.props.history.push("/news/" + item.code);
        this.backList();
    }

    // 查看详情
    lookDetail(item: any) {
        let showDetail = {
            open: true,
            content: item
        }
        this.setState({ showDetail: showDetail });
        saveLocalStorage("showDetail", showDetail);
    }

    // 新增一条
    addList() {
        if (this.state.token !== "admin") {
            message.error("权限不够");
            return
        }
        this.setState({
            isEdit: false,
            editContent: {
                open: true,
                content: {
                    date: "2020-02-02"
                }
            }
        })
    }

    // 返回目录
    backList() {
        let showDetail = {
            open: false,
            content: {}
        };
        this.setState({ showDetail });
        // 如果是权限账号
        if (this.state.token === "admin") {
            // 且编辑过
            if (this.state.editContent.content.guid) {
                this.getNewsData();
            }
        }
        let editContent = {
            open: false,
            content: {
                date: "2019-01-01",
            }
        };
        this.setState({ editContent });
        deleteLocalStorage('showDetail');
    }

    // 编辑此页
    editContent() {
        this.setState({
            isEdit: true,
            editContent: { open: true, content: { ...this.state.showDetail.content } }
        });
    }
    // 关闭编辑
    closeEditContent() {
        if (this.state.editLoading) {
            message.warning("请稍后···")
            return;
        };
        this.setState({ editContent: { open: false, content: { ...this.state.editContent.content } } });
    }
    // 内容变化
    contentChange(key: string, e: any) {
        let data = { ...this.state.editContent };
        data.content[key] = key === "date" ? e : e.target.value;
        this.setState({ editContent: Object.assign({}, this.state.editContent, data) });
    }
    // 确认编辑
    async confirmEditContent() {
        if (this.state.editLoading) {
            message.warning("请稍后···")
            return;
        };
        this.setState({ editLoading: true });
        let data = { ...this.state.editContent };
        // 修改提交
        let flag = this.state.token === "admin" ? true : false;
        if (this.state.isEdit) {
            this.setState({ showDetail: Object.assign({}, this.state.showDetail, data) });
        }
        if (!flag) {
            this.closeEditContent();
            this.setState({ editLoading: false });
            message.success("修改成功");
        } else {
            this.contentFn(data);
        }
    }
    async contentFn(data: any) {
        let isEdit = this.state.isEdit;
        let url, str;
        if (isEdit) {
            url = "editNews";
            str = "修改";
        } else {
            url = "addNews";
            str = "新增";
            data.content.code = this.state.currentUrl;
        }
        let res: any = await postFn(url, data.content);
        this.setState({ editLoading: false });
        if (!res) return;
        if (res.isok) {
            message.success(`${str}成功`);
            this.closeEditContent();
            if (isEdit) return;
            this.getNewsData();
        } else {
            message.success(`因网络延迟${str}失败，请稍后重试`);
        }
    }
    // 获取所有数据
    async getNewsData() {
        this.setState({ loading: true });
        let res: any = await postFn('getNews', {});
        this.setState({ loading: false });
        if (!res) return;
        let data = res.data;
        this.setState({ allData: data });
        this.getCurrenTabData(this.state.currentUrl);
    };
    // 获取当前tab数据
    getCurrenTabData(currentUrl: string) {
        let allData = [...this.state.allData];
        let currentTabData: any = [];
        allData.forEach((el: any) => {
            if (el.code === currentUrl) {
                currentTabData.push(el)
            }
        })
        this.setState({ contentData: currentTabData });
    }
}

export default News;